#include "ringqueue.hpp"
#include "task.hpp"
#include <unistd.h>

const char *str = "+-*/%";
void *producer(void *args)
{
    RingQueue<task> *bq = static_cast<RingQueue<task> *>(args);
    // 向阻塞队列放入任务
    while (true)
    {
        int num1 = rand() % 20;
        int num2 = rand() % 20;
        char symbol = str[rand() % 5];

        task t(num1, num2, symbol);
        bq->push(t);
        cout << "producter[" << pthread_self() << "] " << (unsigned long)time(nullptr) << " 生产了一个任务: " << num1 << symbol << num2 << "=?" << endl;
        sleep(1);
    }
}

void *consumer(void *args)
{
    // 取出任务进行执行
    RingQueue<task> *bq = static_cast<RingQueue<task> *>(args);

    while (true)
    {
        task t = bq->pop();
        int ret = t.dotask();
        int one = 0, two = 0;
        char op = '+';
        t.get(&one, &two, &op);
        cout << "consumer[" << pthread_self() << "] " << (unsigned long)time(nullptr) << " 消费了一个任务: " << one << op <<two << "=" << ret << endl;
    }
}

int main()
{
    RingQueue<task>* rq = new RingQueue<task>;
    srand((unsigned)time(0));
    pthread_t tid1,tid2,tid3,tid4;

    pthread_create(&tid1,nullptr,consumer,(void*)rq);
    pthread_create(&tid2,nullptr,consumer,(void*)rq);
    pthread_create(&tid3,nullptr,producer,(void*)rq);
    pthread_create(&tid4,nullptr,producer,(void*)rq);

    pthread_join(tid1,nullptr);
    pthread_join(tid2,nullptr);
    pthread_join(tid3,nullptr);
    pthread_join(tid4,nullptr);
}